﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using XamlInspector.Annotations;
using XamlInspector.Foundation;

namespace XamlInspector.Model
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void Notify(params string[] propertyNames)
        {
            propertyNames.ForEach(Notify);
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void Notify([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        [NotifyPropertyChangedInvocator]
        protected virtual bool ChangeAndNotify<T>(T value, ref T property, [CallerMemberName] string propertyName = null)
        {
            var hasChanged = Equals(value, property) == false;
            
            if (hasChanged)
            {
                property = value;

                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }

            return hasChanged;
        }
    }
}
